//
//  WxLogin.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/1/11.
//

import Foundation
import SwiftUI
import LeanCloud
import CloudKit
import Contacts

class AppleLogin : BaseViewModel, LoginProtocol {
    
    
    let typeKey = LoginType.APPLE.rawValue
    var userName = "时光"
    let coordinator = AppleSignInCoordinator()
    private let tag = "login"

    func doLogin() {
        // 设置回调
        coordinator.onSignInSuccess = { id, name in
            self.userName = name ?? "时光"
            getLogin(type: LoginType.APPLE)?.doAuthSuc(code: id)
        }
        
        coordinator.onSignInFailure = { error in
            showToast("登陆失败，请检查iCloud账户是否登陆")
        }
        
        // 启动 Apple ID 登录流程
        coordinator.startSignInWithAppleFlow()
    }
    
    func bind() {
        //在代理那边处理
    }
    
    
    func doAuthSuc(code: String) {
        //在代理那边处理
        
    }
    
    func doAuthSuc(access_token: String, openid: String) {
        //无需处理
    }
    
    
    func getAuthInfo(code: String) async throws -> (String, String, UserBean) {
        do {
            let recordID = try await CKContainer.default().userRecordID()
            let iCloudUserID = recordID.recordName
            let newUserBean = UserBean()
            newUserBean.name = userName
            newUserBean.sex = 1
            return (typeKey, iCloudUserID, newUserBean)
        }catch{
            throw MyError.checkParameter(tag, "请登陆iCloud")
        }
    }
    
    func getAuthInfo(access_token: String, openid: String) async throws -> (String, String, UserBean) {
        //无需处理
        return ("","", UserBean())    }
    
    func doLoginAccount(type: String, id: String, newUserBean: UserBean) {
        //在代理那边处理
    }
    
    
    
}
